<template>
  <div class="page-content">
    <div class="title_box">
      <img src="../../assets/img/logo.png" @click.stop="fullscreen" />
      <p class="yx_text">用心自助支付系统</p>
    </div>
    <div class="title_radio">
      <el-radio-group
        v-model="type"
        size="medium"
        @change="isPayData($event)"
        v-if="type == '未支付' || type == '已支付'"
      >
        <el-radio-button label="未支付">未支付</el-radio-button>
        <el-radio-button label="已支付">已支付</el-radio-button>
      </el-radio-group>
      <el-radio-group v-model="type" size="medium" v-if="type == '退货对冲'">
        <el-radio-button label="退货对冲">退货对冲</el-radio-button>
      </el-radio-group>
    </div>
    <!-- <div class="title_icon" v-show="!isFullscreen">
      <i class="el-icon-monitor" @click.stop="fullscreen"></i>
    </div> -->
    <div class="table_box">
      <k-table
        ref="ordertable"
        :data="tableData"
        :showPage="false"
        :isSelection="true"
        :hideScrollBar="true"
        headBg=""
        height="400"
        size="medium"
        v-loading="loading"
        @selectData="selectData"
        @rowClick="rowClick"
      >
        <div
          v-for="(item, index) in tableHeader"
          :key="index"
          style="width: 100%;"
        >
          <el-table-column
            :prop="item.name"
            :label="item.title"
            show-overflow-tooltip
            :align="item.title == '销售价' ? 'right' : 'center'"
            :width="lenList.split(',')[index]"
          >
          </el-table-column>
        </div>
      </k-table>
      <k-table
        ref="tables"
        size="medium"
        :data="detailTableData"
        :showPage="false"
        :hideScrollBar="true"
        headBg=""
        :height="tableHeight"
        v-loading="detailLoading"
      >
        <div
          v-for="(item, index) in detailTableHeader"
          :key="index"
          style="width: 100%;"
        >
          <el-table-column
            :prop="item.name"
            :label="item.title"
            show-overflow-tooltip
            :align="
              item.title == '销售价'
                ? 'right'
                : item.title == '合计'
                ? 'right'
                : 'center'
            "
            :width="lenListsub.split(',')[index]"
          >
          </el-table-column>
        </div>
      </k-table>
    </div>

    <div class="right">
      <div class="key_box">
        <el-form ref="searchForm" :model="searchForm">
          <form-input
            :value="searchForm.khcode"
            label=""
            prop="khcode"
            placeholder="请输入提货码"
            :disabled="true"
          >
          </form-input>
        </el-form>
        <div class="">
          <div class="num" @click="keyClick(1)">1</div>
          <div class="num" @click="keyClick(2)">2</div>
          <div class="num" @click="keyClick(3)">3</div>
          <div class="num" @click="keyClick(4)">4</div>
          <div class="num" @click="keyClick(5)">5</div>
          <div class="num" @click="keyClick(6)">6</div>
          <div class="num" @click="keyClick(7)">7</div>
          <div class="num" @click="keyClick(8)">8</div>
          <div class="num" @click="keyClick(9)">9</div>
          <div class="num no_weight" @click="empty">清空</div>
          <div class="num" @click="keyClick(0)">0</div>
          <div class="num no_weight del" @click="delFn">删除</div>
        </div>
        <div class="submit_btn">
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
        <div class="pay_btn" v-if="selectItem.length > 0">
          <el-button type="primary" @click="goToPay">打印/支付</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      title="收银台"
      width="500px"
      :visible.sync="dvEdit"
      top="30vh"
      custom-class="qrdig"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <p style="font-size:16px">扫一扫付款（元）</p>
      <p class="total">{{ total_amount }}</p>
      <el-image :src="qrCodeUrl" width="230"></el-image>
      <p>扫描二维码支付</p>
    </el-dialog>
  </div>
</template>

<script>
import axios from "@/utils/request";
import screenfull from "screenfull";
import { mapState, mapMutations } from "vuex";
import router from "../../router";
export default {
  inject: ["reload"],
  components: {},
  props: {},
  data() {
    return {
      tableData: [],
      tableHeader: [],
      detailTableData: [],
      detailTableHeader: [],
      loading: false,
      detailLoading: false,
      selectItem: [],
      dvEdit: false,
      qrCodeUrl: "",
      tableHeight: "200",
      searchForm: {
        khcode: ""
      },
      ispay: "",
      total_amount: "",
      lenList: [],
      lenListsub: [],
      qrcodekey: "",
      client_sn: "",
      type: "未支付",
      isFullscreen: false,
      th: false
    };
  },
  watch: {},
  computed: {
    ...mapState({
      user: state => state.user.user
    })
  },
  beforeRouteEnter(to, form, next) {
    next(vm => {
      addEventListener("keydown", vm.handleEvent);
    });
  },
  beforeRouteLeave(to, from, next) {
    removeEventListener("keydown", this.handleEvent);
    next();
  },
  methods: {
    handleEvent(ev) {
      console.log(ev);
      if (ev.keyCode == 8) {
        return (this.searchForm.khcode = this.searchForm.khcode.slice(
          0,
          this.searchForm.khcode.length - 1
        ));
      }
      if (ev.keyCode == 27) {
        return (this.searchForm.khcode = "");
      }
      if (ev.keyCode == 13) {
        return this.submit();
      }
      let num = ev.key.toString().replace(/[^\d]/g, ""); //仅保留数字
      this.searchForm.khcode += num;
    },
    keyClick(val) {
      this.searchForm.khcode += val;
    },
    fullscreen() {
      this.isFullscreen = !this.isFullscreen;
      screenfull.toggle();
    },
    isPayData(val) {
      this.type = val;
      this.getOrder();
    },
    empty() {
      this.searchForm.khcode = "";
      this.tableHeader = [];
      this.tableData = [];
      this.detailTableHeader = [];
      this.detailTableData = [];
    },
    delFn() {
      this.searchForm.khcode = this.searchForm.khcode.slice(
        0,
        this.searchForm.khcode.length - 1
      );
    },
    submit() {
      this.getOrder();
    },
    // 订单
    getOrder() {
      if (this.searchForm.khcode != "") {
        this.loading = true;
        axios
          .get({
            url: "/api/Order/get_order",
            data: {
              gscode: this.user.info.gscode,
              guestcode: this.user.info.reguserno,
              khcode: this.searchForm.khcode,
              type: this.type
            }
          })
          .then(res => {
            this.loading = false;
            if (res.code == "0") {
              if (res.data.length > 0) {
                this.tableHeader = res.filesname;
                this.tableData = res.data;
                this.lenList = res.len;
                for (let index = 0; index < this.tableData.length; index++) {
                  let element = this.tableData[index];
                  element.xsprice = parseFloat(element.xsprice).toFixed(2); //销售价两位小数
                }
                // 表格高度
                this.$nextTick(function() {
                  this.tableHeight = (
                    window.innerHeight -
                    this.$refs.tables.$el.offsetTop -
                    20
                  ).toString();
                  // 监听窗口大小变化
                  let self = this;
                  window.onresize = function() {
                    self.tableHeight = (
                      window.innerHeight -
                      self.$refs.tables.$el.offsetTop -
                      20
                    ).toString();
                  };
                  // this.$refs.table.$el.offsetTop表格距离浏览器的高度
                  // 50表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
                });
              } else {
                this.tableHeader = [];
                this.tableData = [];
                this.detailTableHeader = [];
                this.detailTableData = [];
                this.$message({
                  offset: "500",
                  message: "暂无单据",
                  center: true,
                  duration: "900",
                  type: ""
                });
              }
            } else {
              this.tableHeader = [];
              this.tableData = [];
              this.detailTableHeader = [];
              this.detailTableData = [];
              this.$message({
                offset: "500",
                message: res.msg,
                center: true,
                duration: "900",
                type: ""
              });
              if (res.msg == "已开启退货对冲") {
                this.type = "退货对冲";
                this.th = true;
                this.searchForm.khcode = "";
              }
            }
          })
          .catch(err => {
            this.loading = false;
          });
      }
    },
    // 明细
    getDetail() {
      this.detailLoading = true;
      let tempList = [];
      if (this.selectItem.length > 0) {
        tempList = this.selectItem.map(it => {
          return it.ckpaper;
        });
      }
      axios
        .get({
          url: "/api/Order/get_ordersub",
          data: {
            guestcode: this.user.info.reguserno,
            paperlist: tempList.join()
          }
        })
        .then(res => {
          this.detailLoading = false;
          this.detailTableHeader = res.filesname;
          this.detailTableData = res.data;
          this.lenListsub = res.len;
          for (let index = 0; index < this.detailTableData.length; index++) {
            let element = this.tableData[index];
            element.xsprice = parseFloat(element.xsprice).toFixed(2); //销售价两位小数
            element.sumxsprice = parseFloat(element.sumxsprice).toFixed(2); //销售价两位小数
          }
        })
        .catch(err => {
          this.detailLoading = false;
        });
    },
    // 表格选择
    selectData(val) {
      this.selectItem = val;
      if (this.selectItem.length > 0) {
        this.getDetail();
      } else {
        this.detailTableHeader = [];
        this.detailTableData = [];
      }
    },
    rowClick(row) {},
    // 点击支付获取二维码
    goToPay() {
      let tempList = this.selectItem.map(it => {
        return it.ckpaper;
      });
      let tempList2 = this.selectItem.map(it => {
        if (it.ispay != "") {
          return it.ckpaper;
        }
      });
      axios
        .post({
          url: "/api/pay/core_payment",
          data: {
            guestcode: this.user.info.reguserno,
            gscode: this.user.info.gscode,
            printname: this.user.info.printhost,
            hostname: this.user.info.hostname,
            ywtype: "gateway",
            ddpaper: tempList.join(),
            npaper: tempList2.join()
          }
        })
        .then(res => {
          if (res.code == "0") {
            this.qrCodeUrl =
              "http://wx.inheartsoft.com/2DCode.ashx?data=" +
              encodeURIComponent(res.data);
            this.dvEdit = true;
            this.total_amount = parseFloat(res.total_amount).toFixed(2);
            this.getQRcodeStauts();
            this.qrcodekey = res.qrcode.qrcodekey;
            this.client_sn = res.qrcode.client_sn;
            window.invl = setInterval(this.getQRcodeStauts, 1000);
          } else if (res.code == "2") {
            this.$message({
              offset: "500",
              message: "正在打印，请稍候",
              center: true,
              duration: "900",
              type: ""
            });
            setTimeout(() => {
              if (this.type == "退货对冲") {
                this.clear();
              } else {
                this.refresh();
              }
            }, 1000);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {});
    },
    getQRcodeStauts() {
      if (this.qrcodekey != "" && this.client_sn != "") {
        axios
          .get({
            url: "/api/pay/getStatusPay",
            data: {
              qrcodeKey: this.qrcodekey,
              client_sn: this.client_sn
            }
          })
          .then(res => {
            switch (res.status) {
              case "QRCODE_SCAN_NEVER":
                break;
              case "QRCODE_SCAN_SUCC":
                this.$message({
                  offset: "500",
                  message: "支付成功",
                  center: true,
                  duration: "900",
                  type: ""
                });
                this.closeDialog();
                setTimeout(() => {
                  if (this.type == "退货对冲") {
                    this.clear();
                  } else {
                    this.refresh();
                  }
                }, 1000);
                break;
              case "QRCODE_SCAN_FAIL":
                this.closeDialog();
                break;
            }
          });
      }
    },
    closeDialog() {
      this.qrcodekey = "";
      this.client_sn = "";
      this.dvEdit = false;
      clearInterval(window.invl);
      if (this.type == "退货对冲") {
        this.clear();
      } else {
        this.refresh();
      }
    },
    clear() {
      this.searchForm.khcode = "";
      this.tableHeader = [];
      this.tableData = [];
      this.detailTableHeader = [];
      this.detailTableData = [];
    },
    refresh() {
      this.reload();
    }
  },

  created() {
    if (!this.user.isLogin) {
      router.replace("/login");
    }
  },
  mounted() {}
};
</script>
<style lang="scss" scoped>
.page-content {
  // height: 100vh;
  position: absolute;
  width: 100%;
  height: 100%;
  padding: 50px 20px;
  background: #00acee;
  box-sizing: border-box;
}

.table_box {
  float: left;
  width: 67%;
}

.f_color {
  color: #ff0000;
}

.right {
  float: right;
  width: 30%;
  padding-right: 20px;
}

.table_box .tao-table:nth-child(2) {
  margin-top: 20px;
}

.key_box {
  position: relative;
  width: 90%;
  height: 590px;
  margin: 0 auto;
  padding: 35px 40px;
  text-align: center;
  border-radius: 6px;
  background: #88cce1;
  box-shadow: 0px 0px 10px #666666;
}

>>> .el-input__inner {
  width: 100% !important;
}

>>> .el-input--small .el-input__inner {
  height: 70px;
  line-height: 70px;
  font-size: 40px;
}

>>> .el-input.is-disabled .el-input__inner {
  color: #444951;
}

>>> .el-form-item--small.el-form-item {
  margin-bottom: 30px;
}
>>> .el-table__body tr.current-row > td {
  background-color: #00acee;
  color: #ffffff;
}
.key_box .num:hover {
  cursor: pointer;
}

.key_box .num {
  float: left;
  width: 32%;
  height: 80px;
  line-height: 80px;
  margin-right: 10px;
  margin-bottom: 20px;
  color: #00acee;
  font-size: 40px;
  font-weight: bold;
  box-shadow: 0px 0px 10px #666666;
  border-radius: 4px;
  background: #fff;
}

.key_box .num:nth-child(3n) {
  margin-right: 0;
}

.key_box .no_weight {
  font-size: 20px;
  font-weight: bold;
}

.key_box .del {
  color: #fff;
  background: #f34b4b;
}

.submit_btn {
  .el-button--small,
  .el-button--small.is-round {
    width: 84%;
    position: absolute;
    left: 50%;
    bottom: 0;
    transform: translate(-50%, -50%);
    padding: 24px 0;
    letter-spacing: 2px;
    font-size: 26px;
    background: #01aef0;
    box-shadow: 0px 0px 10px #666666;
  }
}

.title_box {
  text-align: left;
  margin-bottom: 30px;
}

.title_box img {
  width: 70px;
  vertical-align: middle;
  border-radius: 40px;
  margin-right: 10px;
}
.title_radio {
  position: absolute;
  right: 150px;
  top: 60px;
}
>>> .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 180px;
  height: 50px;
  line-height: 30px;
  font-size: 18px;
  background-color: #1f60ba;
  border-color: #1f60ba;
  -webkit-box-shadow: -1px 0 0 0 #1f60ba;
  box-shadow: -1px 0 0 0 #1f60ba;
}
>>> .el-radio-button:first-child .el-radio-button__inner {
  width: 180px;
  height: 50px;
  line-height: 30px;
  font-size: 18px;
}
>>> .el-radio-button:last-child .el-radio-button__inner {
  width: 180px;
  height: 50px;
  line-height: 30px;
  font-size: 18px;
}
.title_icon {
  position: absolute;
  right: 20px;
  top: 50px;
}
.title_icon i {
  font-size: 65px;
  color: #fff;
}
.yx_text {
  display: inline-block;
  vertical-align: middle;
  color: #fff;
  font-size: 40px;
  text-shadow: 3px 3px 3px #666;
  letter-spacing: 2px;
}

.pay_btn {
  width: 84%;
  position: absolute;
  bottom: -50px;
  left: 38%;
  transform: translate(-35%, 50%);
  color: #fff;
  font-size: 26px;
}

.pay_btn {
  .el-button--primary {
    padding: 20px 40px;
    width: 100%;
    border-radius: 6px;
    font-size: 26px;
    background-color: #ff7c00;
    border: none;
    box-shadow: 0px 0px 10px #666666;
  }
}

@media screen and (max-width: 1920px) {
  .key_box .num {
    width: 31.5%;
    height: 80px;
    line-height: 80px;
  }
}

@media screen and (max-width: 1800px) {
  .key_box .num {
    width: 31%;
    height: 80px;
    line-height: 80px;
  }
}

@media screen and (max-width: 1500px) {
  .key_box .num {
    width: 30%;
    height: 80px;
    line-height: 80px;
  }
}

@media screen and (max-width: 1280px) {
  .key_box .num {
    width: 29.5%;
    height: 70px;
    line-height: 70px;
  }

  >>> .el-input--small .el-input__inner {
    font-size: 30px;
  }
}

@media screen and (max-width: 1024px) {
  .page-content {
    padding: 30px;
  }

  .key_box {
    height: 500px;
    padding: 20px;
  }

  .key_box .num {
    width: 21%;
    height: 70px;
    line-height: 70px;
  }

  >>> .el-input--small .el-input__inner {
    font-size: 24px;
  }
}
</style>
<style lang="scss">
.qrdig {
  .el-dialog__title {
    font-weight: bold;
  }

  .el-dialog__body {
    text-align: center;
  }

  .el-image {
    width: 60%;
    padding: 10px;
  }

  p {
    font-size: 20px;
    padding-bottom: 6px;
  }

  .total {
    padding-bottom: 10px;
    color: #ff7c00;
    font-weight: bold;
    font-size: 26px;
  }
}
.negative {
  color: #ff0000;
}
</style>
